# Developer: Qingtian Liu.
# Date: 2024-10-7

import os
import subprocess

def batch_convert_ipynb_to_py(root_directory):
    # 遍历根目录及所有子目录中的文件
    for dirpath, _, filenames in os.walk(root_directory):
        for filename in filenames:
            if filename.endswith(".ipynb"):
                ipynb_file = os.path.join(dirpath, filename)
                # 构建 nbconvert 命令，--to script 转换为 Python 脚本
                convert_command = f'sudo jupyter nbconvert --to script "{ipynb_file}"'
                try:
                    # 执行转换命令并捕获输出
                    result = subprocess.run(convert_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    print(f"Converted: {ipynb_file}")
                except subprocess.CalledProcessError as e:
                    print(f"Failed to convert {ipynb_file}: {e.stderr.decode()}")

# 替换为你想要转换的文件夹路径
root_dir = "/mnt/HDD/qtliuData/statistic_dic/"
batch_convert_ipynb_to_py(root_dir)

